<template>
  <el-row
    type="flex"
    style="width: 100%; margin: 20px 0"
    justify="space-between"
  >
    <el-col> {{ treeNode.name }} </el-col>
    <el-col :span="4">
      <el-row type="flex">
        <el-col>{{ treeNode.manager }}</el-col>
        <el-col>
          <el-dropdown @command="operateDepts">
            <span>操作<i class="el-icon-arrow-down" /></span>
            <el-dropdown-menu>
              <el-dropdown-item command="add">添加子部门</el-dropdown-item>
              <el-dropdown-item
                v-if="!isRoot"
                command="edit"
              >编辑子部门</el-dropdown-item>
              <el-dropdown-item
                v-if="!isRoot"
                command="delete"
              >删除子部门</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script>
import { delDepartment } from '@/api/departments'

export default {
  name: 'TreeTools',
  props: {
    treeNode: {
      type: Object,
      required: true
    },
    isRoot: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    async operateDepts(type) {
      if (type === 'add') {
        this.$emit('addDepts', this.treeNode)
      } else if (type === 'edit') {
        this.$emit('editDepts', this.treeNode)
      } else if (type === 'delete') {
        const confirmText = await this.$confirm('您确定要删除该部门吗？').catch(
          err => err
        )
        // 需要确认删除
        if (confirmText === 'confirm') {
          try {
            await delDepartment(this.treeNode.id)
            // 通知页面刷新当前组织架构列表
            this.$emit('delDepts')
            this.$message.success('删除部门成功')
          } catch (err) {
            this.$message.error(err.message)
          }
        }
      }
    }
  }
}
</script>

<style lang="sass" scoped></style>
